package com.lennon.eoi.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.assertj.core.internal.cglib.beans.BeanCopier;

/**
 * 对象拷贝工具
 * 
 * @author lennon
 *
 */
public class BeanCopierUtils {
	
    public static Map<String,BeanCopier> beanCopierMap = new HashMap<String,BeanCopier>();
   
    //把一个类的所有属性的值对应地赋给另一个类
    public static void copyProperties(Object target, Object source){
        String beanKey =  generateKey(source.getClass(), target.getClass());
        BeanCopier copier =  null;
        if(!beanCopierMap.containsKey(beanKey)){
             copier = BeanCopier.create(source.getClass(), target.getClass(), false);
             beanCopierMap.put(beanKey, copier);
        }else{
             copier = beanCopierMap.get(beanKey);
        }
        copier.copy(source, target, null);
    } 
    
    private static String generateKey(Class<?> class1,Class<?>class2){
        return class1.toString() + class2.toString();
    }
    
    //把一个Map的所有属性的值对应地赋给另一个类
    public static void copyPropertiesFromMap(Object target, Map source) {  
        if (source == null || target == null) {  
            return;  
        }  
        try {  
            BeanUtils.populate(target, source);  
        } catch (Exception e) {  
            System.out.println("transMap2Bean2 Error " + e);  
        }  
    }
}
